package com.zivwu.library.ui.photo;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.zivwu.library.PhotoPicker;
import com.zivwu.library.R;
import com.zivwu.library.dao.bean.Photo;
import com.zivwu.library.ui.image.MediaStoreHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class PhotoPickerActivity extends RxAppCompatActivity implements PopupDirectoryListAdapter.ItemClickListener, ListPhotoFragment.onSelected {
    @Bind(R.id.tv_photo_nav)
    TextView tvPhotoNav;
    @Bind(R.id.fl_photo_nav)
    FrameLayout flPhotoNav;
    @Bind(R.id.tv_center_title)
    TextView tvCenterTitle;
    @Bind(R.id.toolBar)
    Toolbar toolBar;

    private ListPopupWindow popupWindow;

    ListPhotoFragment listPhotoFragment;

    private int canSelectCount = 3;
    private MenuItem menuItem;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ziv_activity_photo_picker);
        ButterKnife.bind(this);
        setSupportActionBar(toolBar);
        tvCenterTitle.setText("图片选择");
        toolBar.setNavigationIcon(R.drawable.ic_back);
        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initPrams(getIntent().getExtras());
        initFragment();
    }


    protected void initPrams(Bundle extras) {
        if (extras == null)
            return;
        canSelectCount = extras.getInt(PhotoPicker.EXTRA_MAX_COUNT, canSelectCount);
    }


    private void initFragment() {
        //获取photos
        Observable.just(this)
                .subscribeOn(Schedulers.io())
                .map(new Function<PhotoPickerActivity, ListPhotoFragment>() {
                    @Override
                    public ListPhotoFragment apply(@NonNull PhotoPickerActivity photoPickerActivity) throws Exception {
                        MediaStoreHelper storeHelper = new MediaStoreHelper(photoPickerActivity);
                        ArrayList<Map.Entry<String, List<Photo>>> entries = storeHelper.getPhotosByModifiedDesc();
                        ArrayList<Photo> photoList = (ArrayList<Photo>) entries.get(0).getValue();
                        initPopupWindow(entries);
                        return ListPhotoFragment.newInstance(canSelectCount, photoList);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleAndroid.<ListPhotoFragment>bindActivity(lifecycle()))
                .subscribe(new Consumer<ListPhotoFragment>() {
                    @Override
                    public void accept(ListPhotoFragment listPhotoFragment) throws Exception {
                        addFragment(listPhotoFragment);
                        flPhotoNav.setVisibility(View.VISIBLE);
                    }
                });

    }


    private void addFragment(Fragment fragment) {
        listPhotoFragment = (ListPhotoFragment) fragment;
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.add(R.id.fl_fragment_photo, fragment, fragment.getClass().getName());
        transaction.commit();
    }


    private void initPopupWindow(ArrayList<Map.Entry<String, List<Photo>>> entries) {
        PopupDirectoryListAdapter dirAdapter = new PopupDirectoryListAdapter(entries);
        dirAdapter.setItemClickListener(this);
        popupWindow = new ListPopupWindow(this);
        popupWindow.setWidth(ListPopupWindow.MATCH_PARENT);
        popupWindow.setHeight(getResources().getDisplayMetrics().heightPixels / 2);
        //获取焦点
        popupWindow.setAdapter(dirAdapter);
        popupWindow.setModal(true);
        popupWindow.setDropDownGravity(Gravity.BOTTOM);
        popupWindow.setAnchorView(tvPhotoNav);
    }

    @Override
    public void onItemClick(Map.Entry<String, List<Photo>> entry) {
        listPhotoFragment.setPhotoData(entry.getValue());
        tvPhotoNav.setText(entry.getKey());
        popupWindow.dismiss();
    }

    @OnClick(R.id.tv_photo_nav)
    public void onViewClicked() {
        popupWindow.show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.ziv_picker_menu, menu);
        menuItem = menu.findItem(R.id.done);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.done:
                onComplete();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    private void onComplete() {
        List<Photo> photoList = listPhotoFragment.getCheckPhotos();
        ArrayList<String> list = new ArrayList<>();
        for (Photo photo : photoList) {
            list.add(photo.getData());
        }
        Intent intent = new Intent();
        intent.putStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS, list);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onSelected(int size) {
        if (size == 0) {
            menuItem.setEnabled(false);
            menuItem.setTitle(getString(R.string.ziv_picker_done));
        } else {
            menuItem.setEnabled(true);
            menuItem.setTitle(getString(R.string.ziv_picker_done_with_count, size, canSelectCount));
        }
    }
}
